package com.jl15988.simpletools.appcore.service.impl;

import com.jl15988.simpletools.appcore.constant.AppConstant;
import com.jl15988.simpletools.appcore.service.FileStorageService;
import com.jl15988.simpletools.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 文件存储服务实现类
 *
 * @author jl15988
 */
@Service
public class FileStorageServiceImpl implements FileStorageService {

    @Value("${file.storage.local-path}")
    private String uploadPath;

    @Override
    public String storeIcon(MultipartFile file, Long appId) {
        String fileName = UUID.randomUUID() + getFileExtension(file.getOriginalFilename());
        String relativePath = AppConstant.STORAGE_ROOT_PATH + "/" + appId + "/" + AppConstant.ICON_PATH + "/" + fileName;
        String fullPath = uploadPath + "/" + relativePath;
        
        try {
            createDirectoryIfNotExists(fullPath);
            file.transferTo(new File(fullPath));
            return relativePath;
        } catch (IOException e) {
            throw new BusinessException("存储应用图标失败: " + e.getMessage());
        }
    }

    @Override
    public String storeScreenshot(MultipartFile file, Long appId, int index) {
        String fileName = index + getFileExtension(file.getOriginalFilename());
        String relativePath = AppConstant.STORAGE_ROOT_PATH + "/" + appId + "/" + AppConstant.SCREENSHOT_PATH + "/" + fileName;
        String fullPath = uploadPath + "/" + relativePath;
        
        try {
            createDirectoryIfNotExists(fullPath);
            file.transferTo(new File(fullPath));
            return relativePath;
        } catch (IOException e) {
            throw new BusinessException("存储应用截图失败: " + e.getMessage());
        }
    }

    @Override
    public String storePackage(MultipartFile file, Long appId) {
        String fileName = UUID.randomUUID() + getFileExtension(file.getOriginalFilename());
        String relativePath = AppConstant.STORAGE_ROOT_PATH + "/" + appId + "/" + AppConstant.PACKAGE_PATH + "/" + fileName;
        String fullPath = uploadPath + "/" + relativePath;
        
        try {
            createDirectoryIfNotExists(fullPath);
            file.transferTo(new File(fullPath));
            return relativePath;
        } catch (IOException e) {
            throw new BusinessException("存储应用包失败: " + e.getMessage());
        }
    }

    @Override
    public String storeCategoryIcon(MultipartFile file, Long categoryId) {
        String fileName = UUID.randomUUID() + getFileExtension(file.getOriginalFilename());
        String relativePath = "categories/" + categoryId + "/" + fileName;
        String fullPath = uploadPath + "/" + relativePath;
        
        try {
            createDirectoryIfNotExists(fullPath);
            file.transferTo(new File(fullPath));
            return relativePath;
        } catch (IOException e) {
            throw new BusinessException("存储分类图标失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteFile(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return false;
        }
        
        String fullPath = uploadPath + "/" + filePath;
        File file = new File(fullPath);
        return file.exists() && file.delete();
    }

    @Override
    public boolean deleteAppFiles(Long appId) {
        String appPath = uploadPath + "/" + AppConstant.STORAGE_ROOT_PATH + "/" + appId;
        return deleteDirectory(new File(appPath));
    }

    /**
     * 递归删除目录
     *
     * @param directory 目录
     * @return 是否成功
     */
    private boolean deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
        }
        return directory.delete();
    }

    /**
     * 创建目录（如果不存在）
     *
     * @param filePath 文件路径
     * @throws IOException IO异常
     */
    private void createDirectoryIfNotExists(String filePath) throws IOException {
        Path path = Paths.get(filePath).getParent();
        if (path != null && !Files.exists(path)) {
            Files.createDirectories(path);
        }
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName 文件名
     * @return 扩展名
     */
    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }
} 